<template>
  <div class="mod-job__schedule">
    <el-form :inline="true" :model="dataForm" @keyup.enter="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.name" placeholder="bean名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <!-- <el-button  @click="edit()">新增流程</el-button> -->
        <el-dropdown placement="bottom-start">
          <el-button type="primary"> 添加监控源 </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="addTemplateFlow()">公众号</el-dropdown-item>
              <el-dropdown-item>新浪微博</el-dropdown-item>
              <el-dropdown-item>搜狐新闻</el-dropdown-item>
              <el-dropdown-item>通用网站</el-dropdown-item>
              <el-dropdown-item @click="edit()">高级流程</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-form-item>
      <!-- <el-form-item>
        <el-button v-if="hasPermission('sys:schedule:delete')" type="danger" @click="deleteHandle()">删除</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="hasPermission('sys:schedule:pause')" type="danger" @click="pauseHandle()">暂停</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="hasPermission('sys:schedule:resume')" type="danger" @click="resumeHandle()">恢复</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="hasPermission('sys:schedule:run')" type="danger" @click="runHandle()">执行</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="hasPermission('sys:schedule:log')" type="success" @click="logHandle()">日志列表</el-button>
      </el-form-item> -->
    </el-form>
    <el-table v-loading="resultData.dataListLoading" :data="resultData.dataList" border style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="name" label="名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="cron" label="cron表达式" header-align="center" align="center"></el-table-column>
      <el-table-column prop="enabled" label="状态" sortable="custom" header-align="center" align="center" width="100">
        <template v-slot="scope">
          <!-- <el-tag v-if="scope.row.enabled === 1" size="small">正常</el-tag>
          <el-tag v-else size="small" type="danger">暂停</el-tag> -->
          <el-switch active-value="1" inactive-value="0" v-model="scope.row.enabled" />
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" show-overflow-tooltip header-align="center" align="center"></el-table-column>
      <el-table-column prop="lastExecuteTime" label="上次执行时间" show-overflow-tooltip header-align="center" align="center"></el-table-column>
      <el-table-column prop="nextExecuteTime" label="下次执行时间" show-overflow-tooltip header-align="center" align="center"></el-table-column>
      <!-- <el-table-column prop="running" label="运行状态" sortable="custom" header-align="center" align="center">
        <template v-slot="scope">
          <el-tag v-if="scope.row.running === 1" size="small">运行中</el-tag>
          <el-tag v-else size="small" type="danger">暂停</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="运行中/已完成" header-align="center" align="center" width="120">
        <template v-slot="scope"> {{ scope.row.running || 0 }} / {{ scope.row.executeCount || 0 }} </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" header-align="center" align="center" width="300">
        <template v-slot="scope">
          <!-- <el-button type="primary" link @click="edit(scope.row.id)" size="small">设计</el-button>
          <el-button type="warning" link @click="cronHandle(scope.row.id, scope.row.cron)" size="small">Cron</el-button>
          <el-button type="warning" link @click="noticeHandle(scope.row.id)" size="small">通知</el-button>
          <el-button type="primary" link @click="logHandle(scope.row.id)" size="small">日志</el-button>
          <el-button type="success" link @click="runHandle(scope.row.id)" size="small">执行</el-button>
          <el-button type="danger" link @click="deleteHandle(scope.row.id)" size="small">删除</el-button> -->
          <el-button-group class="ml-4">
            <el-button type="" :icon="DataLine" @click="edit(scope.row.id)" title="流程设计" />
            <el-button type="" :icon="Calendar" @click="cronHandle(scope.row.id, scope.row.cron)" title="设置Cron" />
            <el-button type="" :icon="Bell" @click="noticeHandle(scope.row.id)" title="设置通知" />
            <el-button type="" :icon="VideoPlay" @click="runHandle(scope.row.id)" title="手动执行" />
            <el-button type="" :icon="Document" @click="logHandle(scope.row.id)" title="日志" />
            <el-button type="" :icon="Delete" @click="deleteHandle(scope.row.id)" title="删除" />
            <!-- <el-button type="primary" link @click="edit(scope.row.id)" size="small">设计</el-button>
            <el-button type="warning" link @click="cronHandle(scope.row.id, scope.row.cron)" size="small">Cron</el-button>
            <el-button type="warning" link @click="noticeHandle(scope.row.id)" size="small">通知</el-button>
            <el-button type="primary" link @click="logHandle(scope.row.id)" size="small">日志</el-button>
            <el-button type="success" link @click="runHandle(scope.row.id)" size="small">执行</el-button>
            <el-button type="danger" link @click="deleteHandle(scope.row.id)" size="small">删除</el-button> -->
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="resultData.page" :page-size="resultData.limit" :size="resultData.total" layout="total, prev, pager, next" :total="resultData.total" @current-change="handleCurrentChange" />
    <notice ref="noticeRef" @refreshDataList="getDataList"></notice>
    <Cron ref="cronRef" @refreshDataList="getDataList" />
    <!-- <logPreview ref="logPreviewRef" /> -->
    <!-- <el-pagination :current-page="resultData.page" :page-sizes="[10, 20, 50, 100]" :page-size="resultData.limit" :total="resultData.total" layout="total, sizes, prev, pager, next, jumper"> </el-pagination> -->
    <!-- 弹窗, 新增 / 修改 -->
    <!-- <add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update> -->
    <!-- 弹窗, 日志列表 -->
    <!-- <log ref="logRef"></log> -->
    <TemplateFlow ref="templateFlowRef" @refreshDataList="getDataList"></TemplateFlow>
  </div>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, onMounted, reactive, Ref, ref, toRefs } from "vue";
import baseService from "@/service/baseService";

import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import notice from "./notice.vue";
import Cron from "./cron.vue";
import TemplateFlow from "./flow/template-flow.vue";
import bus from "@/utils/bus";
import { Bell, Document, Delete, DataLine, Calendar, VideoPlay } from "@element-plus/icons-vue";
const router = useRouter();

const resultData = reactive({
  page: ref(1),
  limit: ref(10),
  dataList: [],
  total: ref(1),
  dataListLoading: ref(false)
});
const handleCurrentChange = (val: number) => {
  resultData.page = val;
  getDataList();
};
const dataListSelections: Ref<never[]> = ref([]);
const getDataList = () => {
  baseService
    .get("spider/list", {
      page: resultData.page,
      limit: resultData.limit
    })
    .then((res) => {
      resultData.dataListLoading = false;
      resultData.dataList = res.data.records;
      resultData.total = Number(res.data.total);
    })
    .catch(() => {
      resultData.dataListLoading = false;
    });
};
const dataForm = ref({
  name: ""
});
const templateFlowRef = ref();
const addTemplateFlow = () => {
  templateFlowRef.value.init();
};
const edit = (id?: string) => {
  // router.push({
  //   path: `/processing/edit`,
  //   query: {
  //     flowId: id
  //   }
  // });
  const { href } = router.resolve({
    path: `/processing/edit`,
    query: {
      flowId: id,
      pop: "true"
    }
  });
  window.open(href, "_blank");
};
const logPreviewRef = ref();
// // 日志列表
const logHandle = (id: string) => {
  logPreviewRef.value.init(id);
};
// 通知
const noticeRef = ref();
const noticeHandle = (id: string) => {
  noticeRef.value.init(id);
};
const cronRef = ref();
const cronHandle = (id: string, cronValue: string) => {
  cronRef.value.init(id, cronValue);
};

const deleteHandle = (id: string) => {
  ElMessageBox.confirm("确定进行[删除]操作?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      baseService.delete(`spider/delete/${id}`, {}).then((res) => {
        ElMessage.success({
          message: "成功",
          duration: 500,
          onClose: () => {
            getDataList();
          }
        });
      });
    })
    .catch(() => {
      //
    });
};
// // 停止
const stopHandle = (id?: string) => {
  if (!id && dataListSelections && dataListSelections.value.length <= 0) {
    return ElMessage({
      message: "请选择操作项",
      type: "warning",
      duration: 500
    });
  }
  ElMessageBox.confirm("确定进行[停止]操作?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      baseService.put(`/spider/stop/${id}`).then((res) => {
        ElMessage.success({
          message: "成功",
          duration: 500,
          onClose: () => {
            getDataList();
          }
        });
      });
    })
    .catch(() => {
      //
    });
};

// // 执行
const runHandle = (id?: string) => {
  if (!id && dataListSelections && dataListSelections.value.length <= 0) {
    return ElMessage({
      message: "请选择操作项",
      type: "warning",
      duration: 500
    });
  }
  ElMessageBox.confirm("确定进行[执行]操作?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      baseService.get(`/spider/run/${id}`).then((res) => {
        ElMessage.success({
          message: "成功",
          duration: 500,
          onClose: () => {
            getDataList();
          }
        });
      });
    })
    .catch(() => {
      //
    });
};

onMounted(() => {
  getDataList();
  // bus.on("getFlowDataListBus", getDataList);
  window.addEventListener("storage", (e) => {
    if (e.key === "sendMessage") {
      console.log(e.newValue); // Hello,Bro!
      getDataList();
    }
  });
});
// 在组件卸载之前移除监听
onBeforeUnmount(() => {
  // bus.off("getFlowDataListBus", getDataList);
});
</script>
